﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.Utilities;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Text.Editor;
//using TwitterAPI;
using VsSpeakerCompanion.UI;
using System.Windows;

namespace VsSpeakerCompanion
{
    [Export(typeof(IWpfTextViewCreationListener))]
    [ContentType("text")]
    [TextViewRole(PredefinedTextViewRoles.Document)]
    internal class WidgetManagerFactory : IWpfTextViewCreationListener
    {
        // The ContentType attribute works for the specified content type or any content type inheriting from it.
        // For example: the TextViewService will be executed when a "CSharp Signature Help" text view is created if we specify ContentType("CSharp") or ContentType("code")
        // So we need to check if the content type is of the specific type we are looking for.
        private readonly string[] SupportedContentTypes = new string[] { "CSharp", "Basic", "XML", "XAML", "CSS" };

        /// <summary>
        /// Export the Adornment Layer used by the VS Speaker
        /// </summary>
        [Export]
        [Order(After = "Caret")]
        [Name("VS Speaker Adornments Layer")]
        private AdornmentLayerDefinition AdornmentLayer { get; set; }

        private IEnumerable<IWidgetProvider> GetOrderedWidgetProviders()
        {
            return Orderer.Order(this.WidgetProviders).Select(export => export.Value);
        }

        /// <summary>
        /// Gets or sets the exported widget providers
        /// </summary>
        [ImportMany]
        private IEnumerable<Lazy<IWidgetProvider, IOrderable>> WidgetProviders { get; set; }

        /// <summary>
        /// Exports an instance of <see cref="TwitterService"/>
        /// </summary>
        [Export(typeof(TwitterAPI.TwitterService))]
		private TwitterAPI.TwitterService TwitterService
        {
            get { return WidgetManager.Instance.TwitterService; }
        }

        /// <summary>
        /// Exports an instance of <see cref="IVisualStudioService"/>
        /// </summary>
        [Export(typeof(IVisualStudioService))]
        private IVisualStudioService VisualStudioService
        {
            get { return WidgetManager.Instance; }
        }

        /// <summary>
        /// Exports an instance of <see cref="IUIService"/>
        /// </summary>
        [Export(typeof(IUIService))]
        private IUIService UIService
        {
            get { return WidgetManager.Instance.UIService; }
        }

        [Import]
        private IServiceProvider serviceProvider { get; set; }

        /// <summary>
        /// This method is called when an instance of <see cref="IWpfTextView"/> is created
        /// </summary>
        /// <param name="textView"></param>
        public void TextViewCreated(IWpfTextView textView)
        {
            // Check if the content type is supported
            if (textView.TextBuffer != null && SupportedContentTypes.Contains(textView.TextBuffer.ContentType.TypeName))
            {
                WidgetManager manager = WidgetManager.Instance;
                manager.ServiceProvider = serviceProvider;
                if (!manager.IsInitialized)
                {
                    try
                    {
                        manager.Initialize(this.GetOrderedWidgetProviders());
                    }
                    catch (Exception ex)
                    {
                        // TODO: Move string to resource file for easier localization
                        MessageBox.Show(string.Format("The Widget Manager could not be initialized. Error: '{0}'", ex.Message), "Error loading Demo Dashboard", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }

                // If the widget manager could be initilized add the view
                if (manager.IsInitialized)
                {
                    manager.Add(textView);
                }
            }
        }
    }
}